<?php
declare (strict_types=1);

namespace app\common\model;

use think\facade\Log;

class Logs extends Base
{
    /**
     * 日志写入数据库
     */
    public static function adds($Description, $emp_id = 0, $emp_name = '系统'): bool
    {
        try {
            parent::create([
                'emp_id' => $emp_id,
                'emp_name' => $emp_name,
                'event' => request()->action(),
                'description' => $Description,
                'ip' => request()->ip()
            ]);

        } catch (\Exception $e) {

            return false;
        }

        return true;
    }

    /**
     * 日志写入文件
     */
    public static function write($route, $msg): bool
    {
        try {
            $method = request()->controller() . '/' . request()->action();
            file_put_contents($route,
                "时间：" . date('Y-m-d H:i:s') . "\r\n
            状态：" . $msg . "\r\n
            IP：" . request()->ip() . "\r\n
            方法：" . $method . "\r\n",
                FILE_APPEND);

        } catch (\Exception $e) {

            return false;
        }

        return true;
    }


    /**
     * 异常日志
     * @param \Exception $e
     * @param string $desc
     * @param false $trace
     */
    public static function exception(\Exception $e, $desc='', $trace=false): void
    {
        try {
            $arr = [
                'desc' => $desc ?: request()->controller().'/'.request()->action(),
                'msg' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine()
            ];
            $trace && $arr['trace'] = $e->getTrace();

            Log::write(json_encode($arr,JSON_UNESCAPED_UNICODE), 'exception');
        } catch (\Exception $e) {
            Log::write("Logs::exception", 'exception');
        }
    }
}